package com.sas.repositoryImpl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.sas.domain.Article;
import com.sas.domain.ArticleField;
import com.sas.repository.ArticleRepository;

@Repository
public class HibernateArticleRepository extends 
HibernateGenericRepository<Article> implements ArticleRepository{
	
	@Autowired
	public HibernateArticleRepository (SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}


	@SuppressWarnings("unchecked")
	public List<Article> findAllSortedBy(String sortName, Boolean asc) {
		Session session = getSession();
		String ascendent = asc ? " asc" : " desc";
		String sql = " from Article order by " + sortName + ascendent;
		Query query = session.createQuery(sql);
		return query.list();
	}


	
	@Override
	public boolean exists(Article art) {
		Session session = getSession();
//		Query query = session.createQuery("select a from Article a where a.code = ?");
		
		Query query = session.createQuery("from Article where code = ?");
		
		
		query.setString(0, art.getCode());
		List<Article> ret = query.list();
		return ret.size() != 0? true: false;
	}

//	@SuppressWarnings("unchecked")
//	public List<T> findAllSortedBy(String property, boolean ascending) {
//		Session session = getSession();
//		String asc = ascending ? " asc" : " desc";
//		String sql = " from "+ domainClass.getName() + " order by " + property + asc;
//		//String sql = " from Article art";
//
//		List<T> result = session.createQuery(sql).list();
//		
//		return result;
//	}

	@Override
	public List<Article> findByArticleField(ArticleField af, String property,
			boolean ascending) {
		Session session = getSession();
		String ascendent = ascending ? " asc" : " desc";
		String sort = "order by  a." + property + " " + ascendent;
		Query query = session.createQuery("select a from Article a inner join a.fields f" +
				" where f = ? "+ sort);
		query.setParameter(0, af);
		
//		query.setString(1, property);
		return query.list();
	}


	@Override
	public Article findByCode(String articleCode) {
		Session session = getSession();
		Query query = session.createQuery("from Article where code = ?");
		query.setString(0, articleCode);
		List<Article> ret = query.list();
		return ret.size() == 0 ? null : ret.get(0);
	}

}
